package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.mongodb.client.result.DeleteResult;
import com.tanhua.dubbo.server.pojo.Managelogs;
import com.tanhua.dubbo.server.pojo.UserManageFrozen;
import com.tanhua.dubbo.server.pojo.UserManageUnfrozen;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service(version = "1.0.0")
public class UserManageApiImpl implements UserManageApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 冻结用户
     *
     * @param adminId            执行冻结管理员id
     * @param userId             被冻结的用户id
     * @param freezingTime       冻结时间，1为冻结3天，2为冻结7天，3为永久冻结
     * @param freezingRange      冻结范围，1为冻结登录，2为冻结发言，3为冻结发布动态
     * @param reasonsForFreezing 冻结原因
     * @param frozenRemarks      冻结备注
     * @return
     */
    @Override
    public Boolean userFreeze(Integer adminId, Integer userId, Integer freezingTime, Integer freezingRange, String reasonsForFreezing, String frozenRemarks) {

        //将数据封装到实体类中进行保存
        //1.第一步进行检验看看MongoDB中是不是已经存在该用户被冻结了
        long count = isUserFrozen(userId);
        if (count > 0) {
            //用户已经被冻结
            return false;
        }
        //2.用户没有被冻结,我们进行保存
        UserManageFrozen userManageFrozen = new UserManageFrozen();
        userManageFrozen.setId(new ObjectId());
        userManageFrozen.setAdminId(adminId);
        userManageFrozen.setUserId(userId);
        userManageFrozen.setFreezingTime(freezingTime);
        userManageFrozen.setFreezingRange(freezingRange);
        userManageFrozen.setReasonsForFreezing(reasonsForFreezing);
        userManageFrozen.setFrozenRemarks(frozenRemarks);
        userManageFrozen.setCreated(System.currentTimeMillis());


        UserManageFrozen save = this.mongoTemplate.save(userManageFrozen);
        //判断一下
        if (ObjectUtil.isNotEmpty(save)) {
            //不为null
            //3.注意此时冻结成功的话,我们还需要保证解冻的地方不存在该用户的信息,保证冻结和解冻只有一个
            //4.先判断存不存在
            try {
                Boolean isNotUserUnfrozen = isUserUnfrozen(userId);
                if (!isNotUserUnfrozen) {
                    //false,则解冻表中,有该用户信息我们需要进行删除
                    Query deleteQuery = Query.query(Criteria.where("userId").is(userId));
                    DeleteResult remove = this.mongoTemplate.remove(deleteQuery, UserManageUnfrozen.class);
                    if (remove.getDeletedCount() > 0) {
                        //保存成功并且删除失败
                        return true;
                    } else {
                        Query delQuery1 = Query.query(Criteria.where("userId").is(userId));
                        DeleteResult remove1 = this.mongoTemplate.remove(delQuery1, UserManageFrozen.class);
                        return false;
                    }

                }
            } catch (Exception e) {
                //防止我们删除失败,我们在这里直接将冻结存储的数据进行删除
                Query delQuery = Query.query(Criteria.where("userId").is(userId));
                DeleteResult remove = this.mongoTemplate.remove(delQuery, UserManageFrozen.class);
                e.printStackTrace();
            }
            //存入完成,删除完成
            return true;
        }
        return false;
    }


    /**
     * 解冻用户
     *
     * @param adminId       执行解冻操作的管理员id
     * @param userId        被解冻的用户id
     * @param frozenRemarks 解冻的原因
     * @return
     */
    @Override
    public Boolean userUnfreeze(Integer adminId, Integer userId, String frozenRemarks) {
        //要解冻的话,在冻结用户里面就含有这个用户,以及在解冻用户中不含有这个用户
        //1.先判断解冻用户中是否含有这个用户
        Boolean isNotUserUnfrozen = isUserUnfrozen(userId);
        if (!isNotUserUnfrozen) {
            //true,就是没有被解冻,用户还是冻结状态
            //false,就是已经被解冻了
            //已经被解冻了就直接返回解冻失败
            return false;

        }
        //2.账户没有解冻,我们进行解冻
        //传入数据
        UserManageUnfrozen userManageUnfrozen = new UserManageUnfrozen();
        userManageUnfrozen.setId(new ObjectId());
        userManageUnfrozen.setAdminId(adminId);
        userManageUnfrozen.setUserId(userId);
        userManageUnfrozen.setFrozenRemarks(frozenRemarks);
        userManageUnfrozen.setCreated(System.currentTimeMillis());

        //3.将数据写入MongoDB中
        UserManageUnfrozen save = this.mongoTemplate.save(userManageUnfrozen);
        //4.判断是否为null
        if (ObjectUtil.isEmpty(save)) {
            //为null,返回false
            return false;
        }

        //5.保存成功的话,我们判断一下冻结表是否存在数据
        Query query = Query.query(Criteria.where("userId").is(userId));
        long count = this.mongoTemplate.count(query, UserManageFrozen.class);
        //判断是否存在
        if (count > 0) {
            try {
                //存在,我们再进行删除
                Query deleteQuery = Query.query(Criteria.where("userId").is(userId));
                DeleteResult remove = this.mongoTemplate.remove(deleteQuery, UserManageFrozen.class);
                if (remove.getDeletedCount() > 0) {
                    return true;
                } else {
                    Query delQuery1 = Query.query(Criteria.where("userId").is(userId));
                    DeleteResult remove1 = this.mongoTemplate.remove(delQuery1, UserManageUnfrozen.class);
                    return false;
                }
            } catch (Exception e) {
                //防止我们删除失败,我们在这里直接将解冻中存储的数据进行删除
                Query delQuery = Query.query(Criteria.where("userId").is(userId));
                DeleteResult remove = this.mongoTemplate.remove(delQuery, UserManageUnfrozen.class);
                e.printStackTrace();
            }

        }

        return true;
    }

    /**
     * 判断用户的是什么状态
     *
     * @param userId
     * @return
     */
    @Override
    public String userStatus(Long userId) {
        //正常1,冻结2
        //1.冻结中是否有
        long count = this.isUserFrozen(Convert.toInt(userId));
        if (count > 0) {
            //用户已经被冻结
            return "2";
        }
        //2.解冻中是否有
        Boolean userUnfrozen = this.isUserUnfrozen(Convert.toInt(userId));
        if (!userUnfrozen) {
            return "1";
        }
        //3.全都没有
        return "1";
    }

    /**
     * 查询日志中的登陆地
     *
     * @param userId
     * @return todo 等日志
     */
    @Override
    public Managelogs getLogs(String userId) {

        Query query = Query.query(Criteria.where("userId").is(Convert.toLong(userId))).with(Sort.by(Sort.Order.desc("logTime")));
        List<Managelogs> managelogsList = this.mongoTemplate.find(query, Managelogs.class);
        if (CollUtil.isEmpty(managelogsList)) {
            Managelogs managelogs = new Managelogs();
            managelogs.setLogTime(System.currentTimeMillis());
            managelogs.setPlace("日志暂无数据");
            return managelogs;
        }
        Managelogs managelogs = managelogsList.get(0);
        return managelogs;
    }

    /**
     * 登录状态
     * 冻结时间，1为冻结3天，2为冻结7天，3为永久冻结
     * 冻结范围，1为冻结登录
     *
     * @param userId
     * @return
     */
    @Override
    public String loginStatus(Long userId) {
        //获取当前时间
        Long nowTime = System.currentTimeMillis();

        //正常1,冻结2
        //冻结中是否有
        UserManageFrozen userManageFrozen = specificUserFrozen(userId);

        //判断是不是味null
        if (ObjectUtil.isNotEmpty(userManageFrozen)) {
            //不为null就已经有被冻结的了

            //获取当前的冻结状态是不是登录冻结
            Integer freezingRange = userManageFrozen.getFreezingRange();
            //判断是不是1,是的话就被冻结
            if (freezingRange == 1) {
                //是的话判断冻结的时间
                Integer freezingTime = userManageFrozen.getFreezingTime();
                Long created = userManageFrozen.getCreated();
                //3day
                if (freezingTime == 1) {
                    //冻结3天
                    //判断当前时间是不是已经到期
                    Long time = 3 * 24 * 60 * 60 * 1000L;
                    if ((nowTime - created) < time) {
                        //还是冻结的
                        return "2";
                    }
                }
                //7day
                if (freezingTime == 2) {
                    //冻结3天
                    //判断当前时间是不是已经到期
                    Long time = 7 * 24 * 60 * 60 * 1000L;
                    if ((nowTime - created) < time) {
                        //还是冻结的
                        return "2";
                    }
                }

                //永久
                if (freezingTime == 3) {
                    //永久冻结
                    return "2";

                }

                //没有冻结或者冻结已经到期
                //是的话就判断是不是被冻结的,是的话就删除表,不是的话就直接返回1
                Query query = Query.query(Criteria.where("userId").is(Convert.toInt(userId)));
                this.mongoTemplate.remove(query, UserManageFrozen.class);

                return "1";

            }

        }

        //是null,就没有被冻结,
        return "1";
    }

    /**
     * 动态发布权限状态
     *
     * @param userId
     * @return
     */
    @Override
    public String publishStatus(Long userId) {
        //获取当前时间
        Long nowTime = System.currentTimeMillis();

        //正常1,冻结2
        //冻结中是否有
        UserManageFrozen userManageFrozen = specificUserFrozen(userId);

        //判断是不是味null
        if (ObjectUtil.isNotEmpty(userManageFrozen)) {
            //不为null就已经有被冻结的了

            //获取当前的冻结状态是不是登录冻结
            Integer freezingRange = userManageFrozen.getFreezingRange();
            //判断是不是1,是的话就被冻结
            if (freezingRange == 3) {
                //是的话判断冻结的时间
                Integer freezingTime = userManageFrozen.getFreezingTime();
                Long created = userManageFrozen.getCreated();
                //3day
                if (freezingTime == 1) {
                    //冻结3天
                    //判断当前时间是不是已经到期
                    Long time = 3 * 24 * 60 * 60 * 1000L;
                    if ((nowTime - created) < time) {
                        //还是冻结的
                        return "2";
                    }
                }
                //7day
                if (freezingTime == 2) {
                    //冻结3天
                    //判断当前时间是不是已经到期
                    Long time = 7 * 24 * 60 * 60 * 1000L;
                    if ((nowTime - created) < time) {
                        //还是冻结的
                        return "2";
                    }
                }

                //永久
                if (freezingTime == 3) {
                    //永久冻结
                    return "2";

                }

                //没有冻结或者冻结已经到期
                //是的话就判断是不是被冻结的,是的话就删除表,不是的话就直接返回1
                Query query = Query.query(Criteria.where("userId").is(Convert.toInt(userId)));
                this.mongoTemplate.remove(query, UserManageFrozen.class);

                return "1";

            }

        }

        //是null,就没有被冻结,
        return "1";
    }

    /**
     * 评论发布权限状态
     *
     * @param userId
     * @return
     */
    @Override
    public String commentStatus(Long userId) {
        //获取当前时间
        Long nowTime = System.currentTimeMillis();

        //正常1,冻结2
        //冻结中是否有
        UserManageFrozen userManageFrozen = specificUserFrozen(userId);

        //判断是不是味null
        if (ObjectUtil.isNotEmpty(userManageFrozen)) {
            //不为null就已经有被冻结的了

            //获取当前的冻结状态是不是登录冻结
            Integer freezingRange = userManageFrozen.getFreezingRange();
            //判断是不是1,是的话就被冻结
            if (freezingRange == 2) {
                //是的话判断冻结的时间
                Integer freezingTime = userManageFrozen.getFreezingTime();
                Long created = userManageFrozen.getCreated();

                //3day
                if (freezingTime == 1) {
                    //冻结3天
                    //判断当前时间是不是已经到期
                    Long time = 3 * 24 * 60 * 60 * 1000L;
                    if ((nowTime - created) < time) {
                        //还是冻结的
                        return "2";
                    }
                }
                //7day
                if (freezingTime == 2) {
                    //冻结3天
                    //判断当前时间是不是已经到期
                    Long time = 7 * 24 * 60 * 60 * 1000L;
                    if ((nowTime - created) < time) {
                        //还是冻结的
                        return "2";
                    }
                }

                //永久
                if (freezingTime == 3) {
                    //永久冻结
                    return "2";

                }

                //没有冻结或者冻结已经到期
                //是的话就判断是不是被冻结的,是的话就删除表,不是的话就直接返回1
                Query query = Query.query(Criteria.where("userId").is(Convert.toInt(userId)));
                this.mongoTemplate.remove(query, UserManageFrozen.class);

                return "1";

            }

        }

        //是null,就没有被冻结,
        return "1";
    }

    /**
     * 判断解冻集合中是不是存在该用户
     *
     * @param userId
     * @return
     */
    private Boolean isUserUnfrozen(Integer userId) {
        //1.通过用户id来判断是不是存在
        Query query = Query.query(Criteria.where("userId").is(userId));
        long count = this.mongoTemplate.count(query, UserManageUnfrozen.class);
        if (count > 0) {
            //用户已经被解冻
            return false;
        }
        //用户没有被解冻
        return true;
    }

    /**
     * 是否被冻结
     *
     * @param userId
     * @return
     */
    private long isUserFrozen(Integer userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        return mongoTemplate.count(query, UserManageFrozen.class);
    }

    private UserManageFrozen specificUserFrozen(Long userId) {
        Integer userId1 = Convert.toInt(userId);
        Query query = Query.query(Criteria.where("userId").is(userId1));
        List<UserManageFrozen> userManageFrozenList = this.mongoTemplate.find(query, UserManageFrozen.class);
        if (CollUtil.isNotEmpty(userManageFrozenList)) {
            return userManageFrozenList.get(0);
        }
        return null;
    }


}
